import * as originate from "@/api/modules/originate"
import {
    deleteUploadFile,
    deleteMultipleUploadFileByPrefix,
    deleteMultipleUploadFile
} from "@/api/cos"
import qs from "qs"
export function OriginateDelete(type, item, commentType = "") {
    return new Promise(async function(resolve, reject) {
        try {
            // 如果存在封面图片
            if (item.img_url) {

                // 整理数据
                let datas = new FormData()
                datas.append('url', item.img_url)
                datas.append("id", item.id)
                datas.append("type", type)
                    // 检测是否可以删除
                const res = await originate.DetectOriginRemove(datas)
                if (res.status == 200) {
                    const regex = /\/([^/]+)$/
                // 如果不存在资源则不删除
                    if(!item.img_url) return 
                    const match = item.img_url.match(regex)
                    console.log(match)
                        // 提取匹配结果中的内容
                    if (match) {
                        // 对匹配字段进行中文解码
                        const lastSegment = decodeURIComponent(match[1])
                        console.log(lastSegment)
                            // 删除多余图片
                        const response = await deleteUploadFile('picture/' + lastSegment)
                        if (response.statusCode == 200 || response.statusCode == 204) {

                        } else {
                            reject(new Error('删除关联文件失败'))
                        }
                    }
                }
            }
            // 如果存在视频
            if (item.video_url) {

                // 整理数据
                let datas = new FormData()
                datas.append('url', item.video_url)
                datas.append("id", item.id)
                datas.append("type", type)
                    // 检测是否可以删除
                const res = await originate.DetectOriginRemove(datas)
                if (res.status == 200) {
                    const regex = /\/([^/]+)$/
                    // 如果不存在资源则不删除
                    if(!item.video_url) return 
                    const match = item.video_url.match(regex)
                        // 提取匹配结果中的内容
                    if (match) {
                        // 对匹配字段进行中文解码
                        const lastSegment = decodeURIComponent(match[1])
                        console.log(lastSegment)
                            // 删除多余图片
                        const response = await deleteUploadFile('video/' + lastSegment)
                        if (response.statusCode == 200 || response.statusCode == 204) {} else {
                            reject(new Error('删除关联文件失败'))
                        }
                    }
                }
            }
            // 如果存在视频
            if (item.document_url) {

                // 整理数据
                let datas = new FormData()
                datas.append('url', item.document_url)
                datas.append("id", item.id)
                datas.append("type", type)
                    // 检测是否可以删除
                const res = await originate.DetectOriginRemove(datas)
                if (res.status == 200) {
                    const regex = /\/([^/]+)$/
                                        // 如果不存在资源则不删除
                                        if(!item.document_url) return 
                    const match = item.document_url.match(regex)
                        // 提取匹配结果中的内容
                    if (match) {
                        // 对匹配字段进行中文解码
                        const lastSegment = decodeURIComponent(match[1])
                        console.log(lastSegment)
                            // 删除多余图片
                        const response = await deleteUploadFile('file/' + lastSegment)
                        if (response.statusCode == 200 || response.statusCode == 204) {

                        } else {
                            reject(new Error('删除关联文件失败'))
                        }
                    }
                }
            }
            // 如果存在乐谱
            if (item.file_code) {
                // 删除指定前缀下的所有文件
                const response = await deleteMultipleUploadFileByPrefix('musicScore/' + item.file_code)
                if (response.statusCode == 200 || response.statusCode == 204) {

                } else {
                    reject(new Error('删除关联文件失败'))
                }
            }
            let formData = new FormData()
            console.log(item)
            formData.append(`${type}_id`, item.id)
            let res
                // 根据类型删除
            switch (type) {
                case 'article':
                    res = await originate.deleteArticleByRoot(formData)
                    break
                case 'video':
                    res = await originate.deleteVideoByRoot(formData)
                    break
                case 'music_score':
                    res = await originate.deleteMusicScoreByRoot(formData)
                    break
                case 'document':
                    res = await originate.deleteDocumentByRoot(formData)
                    break
                case 'user':
                    res = await originate.deleteUserByRoot(formData)
                    break
                case 'tag':
                    res = await originate.deleteTagByRoot(formData)
                    break
                case 'reply':
                    res = await originate.deleteReplyCommentByRoot(formData)
                    break
                case 'comment':
                    formData = new FormData()
                    formData.append("id", item.id)
                    if (!commentType) reject(new Error("未选评论类型"))
                        // 根据评论类型删除
                    switch (commentType) {
                        case 'article':
                            res = await originate.deleteArticleCommentByRoot(formData)
                            break;
                        case 'video':
                            res = await originate.deleteVideoCommentByRoot(formData)
                            break;
                        case 'musicScore':
                            res = await originate.deleteMusicScoreCommentByRoot(formData)
                            break;
                        case 'document':
                            res = await originate.deleteDocumentCommentByRoot(formData)
                            break;
                    }
                    break
            }
            if (res.status == 200) {
                resolve()
            } else if (res.status == 422) {
                reject(new Error(res.msg))
            }
        } catch (error) {
            console.log(error)
            reject()
        }

    })
}

export function OriginateBatchDelete(type, ids, items, commentType = "") {
    return new Promise(async function(resolve, reject) {
        try {
            console.log(ids, items)
            let urls
            if (items) {
                // 判断是否含有资源
                urls = items.map(item => {
                    if (item.img_url || item.video_url || item.document_url) {
                        return item.img_url || item.video_url || item.document_url

                    } else {
                        return null
                    }
                })
            }

            let res

            console.log(urls)
            // 判断urls是否存在空值
            if (urls && urls.some(item => item !== null)) {
                let datas = new FormData()
                datas.append("ids", ids)
                datas.append("type", type)
                    // 添加 urls 数组
                for (let i = 0; i < urls.length; i++) {
                    datas.append("urls[]", urls[i]);
                }
                res = await originate.BatchDetectOriginRemove(datas)
                const regex = /\/([^/]+)$/;

                let match
                    // 如果不存在多余资源
                if (res.status == 200) {
                    // 获取匹配字段
                    let referenced_urls = urls.map(item => {
                        if(!item) return null 
                        match = item.match(regex)
                        if (match) return {
                            Key: decodeURIComponent(match)
                        }
                    })
                    // 过滤空值
                    .filter(item=>item!=null)
                    console.log('referenced_urls', referenced_urls)
                    res = await deleteMultipleUploadFile(referenced_urls)
                    console.log(res)
                    if (res.statusCode == 200 || res.statusCode == 204) {

                    } else {
                        reject(new Error("删除资源失败"))
                    }
                }
                // 如果存在多余资源
                else if (res.status == 422) {
                    if (res.data) {
                        // 获取匹配字段
                        let referenced_urls = res.data.map(item => {
                            match = item.match(regex)
                            if (match) return {
                                Key: decodeURIComponent(match)
                            }
                        })
                        res = await deleteMultipleUploadFile(referenced_urls)
                        if (res.statusCode == 200 || res.statusCode == 204) {

                        } else {
                            reject(new Error("删除资源失败"))
                        }
                    }
                }
            }

            if (type == 'music_score') {
                let response
                    // 是否含有乐谱
                items.forEach(async item => {
                    if (item.hasOwnProperty('file_code')) {
                        // 删除指定前缀下的所有文件
                        response = await deleteMultipleUploadFileByPrefix('musicScore/' + item.file_code)
                        if (response.statusCode == 200 || response.statusCode == 204) {} else {
                            reject(new Error('删除关联文件失败'))
                        }
                    }
                })
            }
            let formData = new FormData()

            formData.append(`${type}_ids`, ids)
            switch (type) {
                case 'article':
                    res = await originate.BatchDeleteArticleByRoot(formData);
                    break;
                case 'video':
                    res = await originate.BatchDeleteVideoByRoot(formData);
                    break;
                case 'music_score':
                    res = await originate.BatchDeleteMusicScoreByRoot(formData);
                    break;
                case 'document':
                    res = await originate.BatchDeleteDocumentByRoot(formData);
                    break;
                case 'comment':
                    if (!commentType) reject(new Error('评论类型为空'))
                    switch (commentType) {
                        case 'article':
                            res = await originate.BatchDeleteArticleCommentByRoot(formData)
                            break;
                        case 'video':
                            res = await originate.BatchDeleteMusicScoreCommentByRoot(formData)
                            break;
                        case 'musicScore':
                            res = await originate.BatchDeleteVideoCommentByRoot(formData)
                            break;
                        case 'document':
                            res = await originate.BatchDeleteDocumentCommentByRoot(formData)
                            break;
                    }
                    break;
                case 'reply':
                    res = await originate.BatchDeleteReplyCommentByRoot(formData);
                    break;
                case 'tag':
                    res = await originate.BatchDeleteTagByRoot(formData);
                    break;
                default:
                    throw new Error('Invalid type');
            }

            if (res.status == 200) {
                resolve()
            } else if (res.status == 422) {
                reject(new Error(res.msg))
            }
        } catch (error) {
            console.log(error)
            reject()
        }

    })
}